import QtQuick
import QtQuick.Layouts
import QtQuick.Controls

Item {
    id:root
    signal indexChanged(int index)

    onIndexChanged: index => {
                        layout.currentIndex = index
                    }

    signal openChat(title:string,sn:string)

    StackLayout {
        id: layout
        anchors.fill: parent
        Rectangle {
            height: parent.height
            // Row {}
            //聊天页
            HSearchBar {
                id: searchBar
                width: parent.width
                height: 70
            }
            Rectangle {
                color: '#f7f7f7'
                anchors.top: searchBar.bottom
                width: parent.width
                height: parent.height - searchBar.height
                Component {
                    id: contactDelegate
                    Rectangle {
                        id: myItem
                        required property string sn
                        required property string nickname
                        required property int latesttime
                        required property string latestmessage
                        required property bool mute
                        required property string icon
                        required property string index
                        required property int unreadmessagecount
                        width: searchBar.width
                        height: 70
                        ContactItemLabel {
                            anchors.fill: parent
                            iconSource: icon
                            nackName: nickname
                            latestMessage: unreadmessagecount
                                           === 0 ? latestmessage : '[' + unReadMessageCount
                                                   + '条] ' + latestmessage
                            timeStamp: {
                                function isCurrentWeek(targetDate) {
                                    const today = new Date()
                                    const dayOfWeek = today.getDay()
                                    // 0(周日)到6(周六)

                                    // 计算本周一（自然周从周一开始）
                                    const monday = new Date(today)
                                    monday.setDate(
                                                today.getDate(
                                                    ) - dayOfWeek + (dayOfWeek === 0 ? -6 : 1))
                                    monday.setHours(0, 0, 0, 0) // 清零时间部分

                                    // 计算本周日
                                    const sunday = new Date(monday)
                                    sunday.setDate(monday.getDate() + 6)
                                    sunday.setHours(23, 59, 59,
                                                    999) // 设为周日最后一毫秒

                                    // 判断目标日期是否在区间内
                                    return targetDate >= monday
                                            && targetDate <= sunday
                                }

                                function isToday(date) {
                                    const today = new Date()
                                    return (date.getFullYear(
                                                ) === today.getFullYear()
                                            && date.getMonth(
                                                ) === today.getMonth()
                                            && date.getDate(
                                                ) === today.getDate())
                                }

                                function isYesterday(date) {
                                    const today = new Date()
                                    const yesterday = new Date(today)
                                    yesterday.setDate(today.getDate() - 1)
                                    return (date.getFullYear(
                                                ) === yesterday.getFullYear()
                                            && date.getMonth(
                                                ) === yesterday.getMonth()
                                            && date.getDate(
                                                ) === yesterday.getDate())
                                }

                                function isWithinOneHour(date) {
                                    const now = new Date()
                                    const diff = now.getTime() - date.getTime()
                                    return diff >= 0 && diff < 3600000
                                }

                                var date = new Date(latesttime * 1000)
                                if (isWithinOneHour(date)) {
                                    const now = new Date()
                                    const diff = (now.getTime(
                                                      ) - date.getTime()) / 1000
                                    //秒
                                    if (diff <= 59) {
                                        return '刚刚'
                                    } else if (diff <= 3600) {
                                        return parseInt(diff / 60, 10) + '分前'
                                    }
                                } else if (isToday(date)) {
                                    Qt.formatDateTime(date, 'HH:mm')
                                } else if (isYesterday(date)) {
                                    return '昨天 ' + Qt.formatDateTime(date,
                                                                     'HH:mm')
                                } else if (isCurrentWeek(date)) {
                                    switch (date.getDay()) {
                                    case 1:
                                        return '星期一'
                                    case 2:
                                        return '星期二'
                                    case 3:
                                        return '星期三'
                                    case 4:
                                        return '星期四'
                                    case 5:
                                        return '星期五'
                                    case 6:
                                        return '星期六'
                                    case 7:
                                        return '星期日'
                                    }
                                } else {
                                    Qt.formatDateTime(date, 'yyyy-MM-dd')
                                }
                            }
                            unReadMessageCount: unreadmessagecount
                            isMute: mute
                        }
                        states: [
                            State {
                                name: "hovered"
                                when: mouseArea.containsMouse && !myItem.focus
                                PropertyChanges {
                                    target: myItem
                                    color: '#eaeaea'
                                }
                            },
                            State {
                                name: "focus"
                                when: myItem.focus && !mouseArea.containsMouse
                                PropertyChanges {
                                    target: myItem
                                    color: '#dedede'
                                }
                            },
                            State {
                                name: "focus and hovered"
                                when: myItem.focus && mouseArea.containsMouse
                                PropertyChanges {
                                    target: myItem
                                    color: '#d3d3d3'
                                }
                            }
                        ]
                        MouseArea {
                            id:mouseArea
                            anchors.fill: parent
                            acceptedButtons: Qt.LeftButton | Qt.RightButton
                            hoverEnabled: true

                            onClicked: mouse => {
                                           if (mouse.button === Qt.LeftButton) {
                                               console.log('左击' + sn)
                                               listView.currentIndex = index
                                               var currentItem =chatMessageModel.get(listView.currentIndex);
                                               root.openChat(currentItem.nickname,currentItem.sn)
                                               unreadmessagecount = 0
                                           } else {
                                               console.log('右击' + sn)
                                               contextMenu.popup()
                                           }
                                       }
                            onPressAndHold: {
                                if (mouse.source === Qt.MouseEventNotSynthesized)
                                    contextMenu.popup()
                            }

                            Panel2Menu {
                                id: contextMenu
                            }
                        }
                    }
                }
                ListView {
                    id: listView
                    anchors.fill: parent
                    model: ChatMessageListModel {
                    id:chatMessageModel
                    }
                    delegate: contactDelegate
                    highlight: Rectangle {
                        color: "#e4e4e4"
                    }
                    focus: true
                    clip: true
                    boundsBehavior: Flickable.StopAtBounds
                    highlightRangeMode: ListView.NoHighlightRange // 不显示高亮范围
                    highlightMoveDuration: 0
                }
            }
        }

        Rectangle {
            //联系人页
            HSearchBar2 {
                id: searchbar2
                width: parent.width
                height: 70
                placeholderText: qsTr("搜索")
            }

            Rectangle {
                anchors.top: searchbar2.bottom
                anchors.horizontalCenter: parent.horizontalCenter
                width: parent.width - 70
                height: 35
                Row {
                    anchors.centerIn: parent
                    Image {
                        width: 23
                        height: 23
                        source: "qrc:/img/icon/群组.png"
                    }
                    Text {
                        text: "通信录管理"
                        font.pixelSize: 14
                        font.family: 'Microsoft YaHei'
                    }
                    spacing: 10
                }
                color: '#ffffff'
                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    onEntered: parent.color = '#ececec' // 鼠标悬停时的颜色
                    onExited: parent.color = '#ffffff' // 鼠标离开时的颜色
                    onClicked: {
                        console.log('通信录管理 clicked')
                    }
                }
            }
        }

        Rectangle {
            //收藏页
            HSearchBar2 {
                id: searchbar3
                width: parent.width
                height: 70
                placeholderText: qsTr("搜索收藏")
            }
        }
    }
}
